package xxx

import (
	shs "gitee.com/asphodelus_dev/simple-hashtable-storage"
	"github.com/tidwall/btree"
	"iter"
)

var _ shs.Index = (*BTreeIndex)(nil)

type BTreeIndex btree.Map[string, uint64]

func NewBTreeIndex() *BTreeIndex {
	return (*BTreeIndex)(btree.NewMap[string, uint64](32))
}

func (B *BTreeIndex) Get(key []byte) (uint64, error) {
	b := (*btree.Map[string, uint64])(B)
	get, exists := b.Get(string(key))
	if !exists {
		return 0, shs.ErrKeyNotFound
	}
	return get, nil
}

func (B *BTreeIndex) Set(key []byte, value uint64) error {
	b := (*btree.Map[string, uint64])(B)
	b.Set(string(key), value)
	return nil
}

func (B *BTreeIndex) Delete(key []byte) error {
	b := (*btree.Map[string, uint64])(B)
	_, exists := b.Delete(string(key))
	if !exists {
		return shs.ErrKeyNotFound
	}
	return nil
}

func (B *BTreeIndex) Iterator() iter.Seq2[[]byte, uint64] {
	return func(yield func([]byte, uint64) bool) {
		b := (*btree.Map[string, uint64])(B)
		it := b.Iter()
		for ok := it.First(); ok; ok = it.Next() {
			if !yield([]byte(it.Key()), it.Value()) {
				return
			}
		}
	}
}
